const app = getApp();

const RongIMLib = app.globalData.RongIMLib;

const RongIMEmoji = app.globalData.RongIMEmoji;


const src = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1550811235181&di=ed6d32826fdda6d72c991071e008cfc8&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01fd3e571dda8032f875a3996cb52f.jpg%402o.jpg";

var params = {
    appKey: "x18ywvqfxc6nc",
    self: null
};


Page({
    data: {
        user_data:'',                // 用户微信端数据

        this_id: "",                 // 自己的用户id
        user_id: "",                 // 当前聊天对方用户id
		user_name:"",				 // 当前聊天对方用户名
        
        auction_id: "",            	 // 活动id
		room_id:"chatRoomId-008",	 // 聊天室id

        message: '',                 // 发送的消息
        toView:'',                   // 当前消息id
        messageList: [],             // 消息记录

        emojiList:[],                // 表情数据

        scrollHeight:0,
        keyboardHeight:0,            // 键盘高度

        isAllowScroll:true,         // 是否加载中
        hasMsg:true,                 // 是否有历史记录
    },
    // 输入消息
    inputMessage(e) {
        this.setData({ message: e.detail.value })
    },
	// 输入框获取焦点
    focusEvent(e){
		
	},
    // 输入框失去焦点
    blurEvent(e){
        this.setData({
            faceEmojiShow:false,
            verbalTrickShow: false,
        })
    }, 
    // 显示表情列表
    showFaceEmoji(){
        this.setData({
            verbalTrickShow:false,
            faceEmojiShow:true
        })
    },
    // 选择表情
    selectFaceEmoj(e){
        var self = this;
        var emoji = e.target.dataset.emoji;
        var message = this.data.message;
        this.setData({
            verbalTrickShow: false,
            message: message + emoji
        })
    },
    // 获取聊天记录
    // getMoreMessages: function (event) {
    //     getMoreMessages(this);
    // },
    // 发送消息
    sendMessage(e) {
        var message = this.data.message;
        this.setData({
            faceEmojiShow: false,
            verbalTrickShow: false,
        })
		if (!message){
			wx.showToast({
				image:'../../img/warning.png',
				title: '请输入内容',
			})
		}else{
			sendMessage(this, message);
		}
        
    },
    onLoad: function (options) {
        var self = this;
        
        var user_id = options.user_id;   // 对方id
        var goodsDetail = options.goodsDetail ? options.goodsDetail: {};
        // params.user_id = opponent ? + opponent : this.data.room_id;    // 聊天室id
        params.user_id = user_id;    // 聊天室id
        params.self = this;


		this.setData({
            goodsDetail,
			user_name: options.name || "XXX",
            user_id,
			this_id: app.globalData.User_id
		})

		this.dialog = this.selectComponent("#dialog");
        this.dialog_repeal = this.selectComponent("#dialog-repeal");
        this.dialog_phone = this.selectComponent("#dialog-phone");
        this.dialog_shut_up = this.selectComponent("#dialog-shut-up");
		this.dialog_start_auction = this.selectComponent("#dialog-start-auction");

        this.login = this.selectComponent("#login");

		this.loginLoad();
        app.globalData.writeInContent = writeInContent;
    },
	// 登录后加载数据
	loginLoad(){
		var self = this;

		wx.getStorage({
			key: 'user',
			success: function (res) {
                self.getUserInfo();
                self.rongIMLibInit();       // 初始化融云
			},
			fail() {
				wx.login({
					success: res => {
						wx.request({
							url: app.url.requestUrl + '/login/login',
							method: 'POST',
							data: {
								code: res.code
							},
							success: function (data) {
                                var datas = data.data;
								if (data.data.code == 1) {
									wx.setStorage({
										key: 'user',
										data: data.data.data
									})
                                    self.getUserInfo();
                                    self.rongIMLibInit();           // 初始化融云
								}
								if (datas.code == -1) {
									self.loginOverdue()
								}
							}
						})
					}
				})
			}
		})
	},
	onReady(){
		var user_name = this.data.user_name;
		wx.setNavigationBarTitle({ title: '与' + user_name + '聊天' })
	},
    // 卸载页面
    onUnload(){
        var self = this;
        // console.log("卸载页面吧" + params.room_id)
        // var chatRoomId = params.room_id; // 聊天室 Id。
        // RongIMClient.getInstance().quitChatRoom(chatRoomId, {
        //     onSuccess: function () {
        //         console.log("退出聊天室成功")
        //         params.self.setData({
        //             messageList:[],
        //         })
        //     },
        //     onError: function (error) {
        //         console.log("退出聊天室失败")
        //     }
        // });
    },
    // 登录授权
    getUserInfo(){
        var self = this;
        //获取用户信息
        wx.getSetting({
            success: res => {
                if (!res.authSetting['scope.userInfo']) {
                    console.log("未授权");
                    this.login.showModalBox()
                }else{
                    console.log("已授权");
                    //已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success(res) {
                            wx.setStorage({
                                key: 'user_info',
                                data: res.userInfo,
                            })
                            self.setData({
                                user_data: res.userInfo
                            })
                        }
                    })
                }
            }
        })
    },
    // 确认授权登录
    __accreditEvent(e) {
        this.uploadUserInfo(e.detail.user_info)
        this.login.hideModalBox()
    },
    // 登录成功上传头像及用户信息
    uploadUserInfo(info){
        var self = this;
        var url = "/user/save_user_info";
        var name = info.nickName;
        var header_img = info.avatarUrl

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        name,
                        header_img
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1){
                            wx.setStorage({
                                key: 'user_info',
                                data: info,
                            })
                            self.setData({
                                user_data: info
                            })
                        }
                    }
                })
            }
        })
    },
    // 初始化融云
    rongIMLibInit() {
        var self = this;
        getHistoryList(20,true)
    },
	// 登录过去状态
	loginOverdue(e) {
		var self = this;
		wx.removeStorage({
			key: 'user',
			success: function(res) {
				self.loginLoad();
			},
		})
	},
    // 下拉获取历史记录
    getHistoryList(){
        var hasMsg = this.data.hasMsg;
        if (hasMsg){
            this.setData({ isAllowScroll : true})
            getHistoryList(5);
        }else{
            this.setData({ isAllowScroll : false })
        }
    }
})

// 获取 emoji 表情数据列表
function getEmojiList(){
    var list = RongIMEmoji.list;
    var horizontal = 8;
    var vertical = 3;
    var length = -1; 
    var emojiList = [];

    list.map(function(item,index){
        if (index % (horizontal * vertical) == 0){
            length++;
            emojiList[length] = [];
        }
        emojiList[length].push(item)
    })
    params.self.setData({
        emojiList: emojiList ,
    })
}

// 发送文本消息
function sendMessage(self, text, type) {
    type = type || "text";

    var targetId = params.user_id;

    var extra = {
        nickname: params.self.data.user_data.nickName,
        photo: params.self.data.user_data.avatarUrl,
        data_type: type
    }

    var msg = new RongIMLib.TextMessage({ content: text, extra: extra });
    var conversationType = RongIMLib.ConversationType.PRIVATE;  // 私聊
    var messageList = params.self.data.messageList;                // 消息数据列表

    RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, targetId, msg, {
        onSuccess: function (message) {
            //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
            messageList.push({
                messageType: 'text',
                content: message.content.content,
                userInfo: {
                    user_id: message.senderUserId,
                    nickname: message.content.extra ? message.content.extra.nickname : '何小理1',
                    photo: message.content.extra ? message.content.extra.photo : src,
                    data_type: message.content.extra ? message.content.extra.data_type : 'text',
                },
                messageUId: message.messageUId
            })

            params.self.setData({
                message: '',
                toView: message.messageUId,
                messageList: messageList
            })
            console.log("发送文本消息成功");
        },
        onError: function (errorCode, message) {
            var info = '';
            switch (errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                    info = '超时';
                    break;
                case RongIMLib.ErrorCode.UNKNOWN:
                    info = '未知错误';
                    break;
                case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                    info = '在黑名单中，无法向对方发送消息';
                    break;
                case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                    info = '不在讨论组中';
                    break;
                case RongIMLib.ErrorCode.NOT_IN_GROUP:
                    info = '不在群组中';
                    break;
                case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                    info = '不在聊天室中';
                    break;
                default:
                    info = x;
                    break;
            }
            console.log('发送失败:' + info);
        }
    })
}

// 获取 聊天历史
function getHistoryList(count, isFirst) {
    var conversationType = RongIMLib.ConversationType.PRIVATE; //单聊,其他会话选择相应的消息类型即可。
    var targetId = params.user_id; // 想获取自己和谁的历史消息，targetId 赋值为对方的 Id。
    if (isFirst) {
        var timestrap = 0; // 默认传 null，若从头开始获取历史消息，请赋值为 0 ,timestrap = 0;
    } else {
        var timestrap = null;
    }

    var count = count; // 每次获取的历史消息条数，范围 0-20 条，可以多次获取。
    RongIMLib.RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, timestrap, count, {
        onSuccess: function (list, hasMsg) {
            // if (list.length == 0 && params.self.data.messageList.length && !params.is_request) {
            //     params.self.onLoad({ user_id: params.user_id });
            //     wx.setStorage({
            //         key: params.this_id + 'chat' + params.user_id,
            //         data: true,
            //     })
            // }
            params.self.setData({ hasMsg })
            list.map((item, index) => {
                switch (item.messageType) {
                    case RongIMLib.RongIMClient.MessageType.TextMessage:
                        var messageList = params.self.data.messageList;
                        if (isFirst) {
                            messageList.push({
                                messageType: 'text',
                                content: item.content.content,
                                userInfo: {
                                    user_id: item.senderUserId,
                                    nickname: item.content.extra ? item.content.extra.nickname : '何小理1',
                                    photo: item.content.extra ? item.content.extra.photo : src,
                                    data_type: item.content.extra ? item.content.extra.data_type : 'text'
                                },
                                messageUId: item.messageUId
                            })
                        } else {
                            messageList.unshift({
                                messageType: 'text',
                                content: item.content.content,
                                userInfo: {
                                    user_id: item.senderUserId,
                                    nickname: item.content.extra ? item.content.extra.nickname : '何小理1',
                                    photo: item.content.extra ? item.content.extra.photo : src,
                                    data_type: item.content.extra ? item.content.extra.data_type : 'text'
                                },
                                messageUId: item.messageUId
                            })
                        }
                        params.self.setData({
                            toView: item.messageUId,
                            messageList: messageList
                        })
                        break;
                    default:
                }
            })
            // list => Message 数组。
            // hasMsg => 是否还有历史消息可以获取。
        },
        onError: function (error) {
            console.log("GetHistoryMessages,errorcode:" + error);
        }
    });

    getEmojiList()
}

// 写入文本消息
var writeInContent = function (num, message) {
    var messageList = params.self.data.messageList;
    
    messageList.push({
        messageType: 'text',
        content: message.content.content,
        userInfo: {
            user_id: message.senderUserId,
            nickname: message.content.extra ? message.content.extra.nickname : '何小理1',
            photo: message.content.extra ? message.content.extra.photo : src,
            data_type: message.content.extra ? message.content.extra.data_type : 'text'
        },
        messageUId: message.messageUId
    })

    params.self.setData({
        message: '',
        toView: message.messageUId,
        messageList: messageList
    })
}